import { Injectable } from '@nestjs/common';
// import { ConfigService } from '@nestjs/config';
import { Gather } from './gather.entity';
import { DataSource, In, Like, Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { AppGatherDtoParams } from './dto/list.dto';
import { Collection } from '../collection/collection.entity';
import { History } from '../history/history.entity';
import { lineToHumpObject } from 'src/utils/change-case.util';
import { Article } from '../article/article.entity';
// import { PassThrough } from 'stream';
@Injectable()
export class AppGatherService {
  constructor(
    @InjectRepository(Gather)
    private readonly appGatherRepository: Repository<Gather>,
    @InjectRepository(Collection)
    private readonly appCollectionRepository: Repository<Collection>,
    @InjectRepository(History)
    private readonly appHistoryRepository: Repository<History>,
    @InjectRepository(Article)
    private readonly appArticleRepository: Repository<Article>,
    private readonly dataSource: DataSource,
  ) {}

  async findAll(params: AppGatherDtoParams): Promise<Gather[]> {
    const gathers = await this.appGatherRepository.find({
      where: {
        classificationId: params.classificationId,
        name: Like(`%${params.name}%`),
      },
    });
    return gathers;

    // // 首先查询所有 vip = 0 的用户
    // const gathers = await this.appGatherRepository.find({
    //   where: {
    //     classificationId: params.classificationId,
    //     name: Like(`%${params.name}%`),
    //   },
    // });

    // // 创建一个映射来存储 userId 和对应的 articleTotal
    // const articleTotals = await this.appArticleRepository
    //   .createQueryBuilder('article')
    //   .select('article.gatherId, COUNT(article.id) as article_total')
    //   .groupBy('article.gatherId')
    //   .getRawMany();

    // // 创建一个映射对象以便快速查找
    // const articleTotalCountMap = articleTotals.reduce(
    //   (map, item) => {
    //     map[item.gather_id] = item.article_total;
    //     return map;
    //   },
    //   {} as Record<number, number>,
    // );
    // // 为每个用户添加 articleTotal 字段
    // return gathers.map((gather) => ({
    //   ...gather,
    //   articleTotal: articleTotalCountMap[gather.id] || 0, // 如果找不到对应的 articleTotal，则默认为 0
    // }));
    // const { pageSize, pageNum } = params;
    // return items;
    // return {
    //   records: items,
    //   total,
    //   pageSize,
    //   current: pageNum,
    //   pages: Math.ceil(total / pageSize),
    // };
    // const [items] = await this.AppGatherRepository.findAndCount({});
    // return items;
    // return await this.userRepository
    //   .createQueryBuilder()
    //   .where({ deleted: 0 })
    //   .select(['user_name', 'email'])
    //   .getMany();
    //   .find();
  }

  async findCollectionList(userId): Promise<Gather[]> {
    const gatherIds = await this.appCollectionRepository.find({
      where: {
        userId,
        // type: 1,
      },
      select: ['gatherId'],
    });
    const gathers = await this.appGatherRepository.find({
      where: {
        id: In(gatherIds.map((item) => item.gatherId)),
      },
    });
    return gathers;

    // // 首先查询所有 vip = 0 的用户
    // const gathers = await this.appGatherRepository.find({
    //   where: {
    //     classificationId: params.classificationId,
    //     name: Like(`%${params.name}%`),
    //   },
    // });

    // // 创建一个映射来存储 userId 和对应的 articleTotal
    // const articleTotals = await this.appArticleRepository
    //   .createQueryBuilder('article')
    //   .select('article.gatherId, COUNT(article.id) as article_total')
    //   .groupBy('article.gatherId')
    //   .getRawMany();

    // // 创建一个映射对象以便快速查找
    // const articleTotalCountMap = articleTotals.reduce(
    //   (map, item) => {
    //     map[item.gather_id] = item.article_total;
    //     return map;
    //   },
    //   {} as Record<number, number>,
    // );
    // // 为每个用户添加 articleTotal 字段
    // return gathers.map((gather) => ({
    //   ...gather,
    //   articleTotal: articleTotalCountMap[gather.id] || 0, // 如果找不到对应的 articleTotal，则默认为 0
    // }));
    // const { pageSize, pageNum } = params;
    // return items;
    // return {
    //   records: items,
    //   total,
    //   pageSize,
    //   current: pageNum,
    //   pages: Math.ceil(total / pageSize),
    // };
    // const [items] = await this.AppGatherRepository.findAndCount({});
    // return items;
    // return await this.userRepository
    //   .createQueryBuilder()
    //   .where({ deleted: 0 })
    //   .select(['user_name', 'email'])
    //   .getMany();
    //   .find();
  }

  async findOne(id: number) {
    const history = await this.appHistoryRepository.findOne({
      where: {
        gatherId: id,
      },
      select: ['progress'],
    });
    const gather = await this.appGatherRepository.findOne({
      where: {
        id,
      },
    });
    gather.progress = history?.progress;
    return gather;
  }

  async findGatherByIdAndCheckFollow(id: number, userId: string) {
    // const gather = await this.appGatherRepository
    //   .createQueryBuilder('gather')
    //   // .leftJoinAndSelect('gather.user', 'user')
    //   .leftJoinAndSelect('gather.collections', 'collection')
    //   .leftJoinAndSelect('collection.user', 'user')
    //   .addSelect((subQuery) => {
    //     return subQuery
    //       .select('COUNT(*)', 'isCollected')
    //       .from(Collection, 'c')
    //       .where('c.gatherId = gather.id')
    //       .andWhere('c.userId = :userId', { userId });
    //   }, 'isCollected')
    //   .where('gather.id = :id', { id })
    //   .getOne();
    // const gather = await this.appGatherRepository.executeSqlQuery({
    //   where: { id },
    //   relations: ['collections', 'collections.user'],
    // });
    const gather = await this.dataSource.query(`
      SELECT 
          g.*, 
          h.progress,
          (SELECT COUNT(*) 
          FROM collection col 
          WHERE col.gather_id = g.id 
          AND col.user_id = '${userId}') AS is_collected
      FROM 
          gather g
      LEFT JOIN 
          collection c ON g.id = c.gather_id
      LEFT JOIN 
          app_user u ON c.user_id = u.user_id
      LEFT JOIN 
          history h ON h.user_id = u.user_id  AND h.gather_id = ${id}
      WHERE g.id = ${id};
    `);
    if (gather?.length > 0) {
      return lineToHumpObject(gather[0]);
    } else {
      return null;
    }
  }

  /**
   * 更新文章数量字段
   */
  async updateArticleTotal(gatherId: number) {
    const total = await this.appArticleRepository.count({
      where: {
        gatherId,
      },
    });
    this.appGatherRepository
      .createQueryBuilder()
      .update('gather')
      .set({
        articleTotal: total,
      })
      .where('id = :id', { id: gatherId })
      .execute();
    return total;
  }
}
